var ItemCode = $("input[name='Code']"),
    ItemName = $("input[name='Name']"),
    ItemLevel = $("input[name='Level']"),
    ItemPCode = $("input[name='PCode']"),
    ItemIcon = $("div[name='Icon']"),
    //ItemTitle = $('.u_pane_header h4 span'),
    mCode = $('#m_Code'),
    mName = $('#m_Name'),
    mLevel = $('#m_Level'),
    mPCode = $('#m_PCode'),
    mIconPath = $('#m_IconPath'),
    tree = $('#jstree_folders'),
    _grid = $("#jgTable"),
    //pager = $("#jgPager");
    gridWidth = $('.u_pane_2 .u_block_content');

var Data = [],
    Code = '',
    Name = '',
    Level = '';

var jg_postData = {
    Method: 'Q',
    Content:{
        PCode: 0,
        Level: 1,
        SearchText: ''
    }
};
for(i in postData){
    jg_postData[i] = postData[i];
};

$(function () {
    //产品类别详情
    treeInit();
    requestAjax01();
    $('li[data-opt="edit"]').on('click', function(){
        if(Code){
            nodeEdit();
        }else{
            myAlert('请选择您要编辑的类别');
        }
    });
    $('li[data-opt="delete"]').on('click', function(){
        if(Code){
            nodeDelete();
        }else{
            myAlert('请选择您要删除的类别');
        }
    });
    $('li[data-opt="new1"]').on('click', function(){
        if(Code){
            nodeNew1();
        }else{
            myAlert('请选择您要编辑的类别');
        }
    });
    $('li[data-opt="new2"]').on('click', function(){
        if(Code){
            nodeNew2();
        }else{
            myAlert('请选择您要编辑的类别');
        }
    });
    $('li[data-opt="link"]').on('click', function(){
        pageNew(Code);
    });
    tree.on("changed.jstree", function (e, data) {
        //console.log(data.action) //deselect_all,select_node,ready
        if (data.action === 'select_node') {
            //console.log('选中节点')
            Code = data.node.li_attr.Code;
            Name = data.node.li_attr.Name;
            Level = data.node.li_attr.level;
            requestAjax02();
            jg_postData.Content = {
                PCode: Code,
                Level: Level + 1,
                SearchText: ''
            }
            _grid.trigger("reloadGrid");
        }else if(data.action === 'deselect_all') {
            //console.log('加载完成')
            tree.jstree('open_all');
            //var Selected = $('li[code="CA0265"]');
            //Selected.find('>a').trigger('click');
        }
    });
    $('#modal-overlay .modal-data').draggable();
    $('.form-group .u_item').on('click', addPictures);
    //产品类别排序
    _gridInit();
    $('#categoryBtn').on('click', function(){
        jg_postData.Content = {
            PCode: 0,
            Level: 1,
            SearchText: ''
        }
        _grid.trigger("reloadGrid");
    });
    $('#sortBtn').on('click', requestAjax04);
    $('.u_tab_2').on('click',function(){
        $('.u_pane_1').addClass('hidden');
        $('.u_pane_2').removeClass('hidden');
        gridSize();
    });
    $('.u_tab_1').on('click',function(){
        $('.u_pane_2').addClass('hidden');
        $('.u_pane_1').removeClass('hidden');
    });
});


//产品类别详情

function context_menu(){
    var items = {
        'Open': {
            'label': '品牌数据',
            'action': function (obj) { 
                pageNew(Code);
            }
        },
        'Edit': {
            'label': '编辑',
            'action': nodeEdit
        },
        'Delete': {
            'label': '删除',
            'action': nodeDelete
        },
        'New1': {
            'label': '新建同级',
            'action': nodeNew1
        },
        'New2': {
            'label': '新建子级',
            'action': nodeNew2
        }
    };
    return items;
}

function requestAjax01(){   //MDM000302
    $.ajax({
        async: false,
        type: "post",
        url: mdmPath + "/MDM0003/MDM000302",
        data: {
            Method: 'Q',
            Tonken: postData.Tonken,
            UserCode: postData.UserCode,
            BrowserID: postData.BrowserID,
            Source: postData.Source
        },
        dataType: "json",
        success: function(re) {
            loadAjax01(re);
        }
    });
}
function loadAjax01(re){
    re.Status == -999 && alert_QX($('body'),re.Message);

    Data = re.Content;
    //Data = [];
    if(Data.length>0){
        treeRefresh();    
    }else{
        firstNodeNew();
    }
}

function requestAjax02(){   //MDM000303
    var _postData = {
        Method: 'Q',
        Content: {
            Code: Code
        }
    }
    for(i in postData){
        _postData[i] = postData[i];
    }
    $.ajax({
        async: false,
        type: "post",
        url: mdmPath + "/MDM0003/MDM000303",
        data: _postData,
        dataType: "json",
        success: function(re) {
            loadAjax02(re);
        }
    });
}
function loadAjax02(re){
    if (re.Status == 200) {
        ItemCode.val(re.Content.Code);
        ItemName.val(re.Content.Name);
        ItemLevel.val(re.Content.Level);
        ItemPCode.val(re.Content.PCode);
        if(re.Content.IconPath){
            ItemIcon.html('<img src='+PicAddress+re.Content.IconPath+'>')
        }else{
            ItemIcon.html('<a href="javascript:0"></a>')
        }
    } else if (re.Status == -999){
        alert_situ($('.u_pane_1').find('.form-horizontal'),re.Message);
    } else {
        myAlert(re.Message);
    }
}

// options
function pageNew(Code){
    if(Level==1){
        window.open('MDM000302.html?Code=' + Code, '_blank');
    }else{
        myAlert('请选择一个一级类别');
    } 
}
function nodeNew1(){
    mPCode.val(ItemPCode.val());
    mLevel.val(ItemLevel.val());
    mCode.val('0').attr('disabled', true);
    mName.val('');
    mIconPath.val('');
    mIconPath.next().find('.u_item').html('<a href="javascript:0"></a>');
    $('#modal-overlay').removeClass('hidden');
    $('#submitBtn').unbind('click').bind('click', function(){
        var _postData = {
            Method: 'A'
        }
        requestAjax03(_postData);
    })
}
function nodeNew2(){
    mPCode.val(ItemCode.val());
    mLevel.val(parseInt(ItemLevel.val())+1);
    mCode.val('0').attr('disabled', true);
    mName.val('');
    mIconPath.val('');
    mIconPath.next().find('.u_item').html('<a href="javascript:0"></a>');
    $('#modal-overlay').removeClass('hidden');
    $('#submitBtn').unbind('click').bind('click', function(){
        var _postData = {
            Method: 'A'
        }
        requestAjax03(_postData);
    })
}
function firstNodeNew(){
    $('.u_fixed_row').append('<a href="javascript:0" class="firstBtn">开始创建第一条数据</a>');
    $('.firstBtn').on('click', function(){
        mPCode.val(0);
        mLevel.val(1);
        mCode.val('').attr('disabled', false);
        mName.val('');
        $('#modal-overlay').removeClass('hidden');
            $('#submitBtn').unbind('click').bind('click', function(){
            var _postData = {
                Method: 'A'
            }
            requestAjax03(_postData);
            $('.firstBtn').remove();
        })
    })
}
function nodeEdit(){
    mPCode.val(ItemPCode.val());
    mLevel.val(ItemLevel.val());
    mCode.val(ItemCode.val()).attr('disabled', true);
    mName.val(ItemName.val());
    if(ItemIcon.find('img').length>0){
        var src = ItemIcon.find('img')[0].src.split(PicAddress)[1];
        mIconPath.val(src);
        mIconPath.next().find('.u_item').html('<img src="'+PicAddress+src+'">');
    }else{
        mIconPath.val('');
        mIconPath.next().find('.u_item').html('<a href="javascript:0"></a>');
    }
    $('#modal-overlay').removeClass('hidden');
    $('#submitBtn').unbind('click').bind('click', function(){
        var _postData = {
            Method: 'U'
        }
        requestAjax03(_postData);
    })
}
function nodeDelete(){
    console.log(ItemCode.val())
}

function requestAjax03(_postData){  //MDM000301
    _postData.Content = {
        Code: mCode.val(),
        Name: mName.val(),
        Level: mLevel.val(),
        PCode: mPCode.val(),
        IconPath: mIconPath.val()
    };
    for(i in postData){
        _postData[i] = postData[i];
    };
    console.log(_postData)
    $.ajax({
        type: "post",
        url: mdmPath + "/MDM0003/MDM000301",
        data: _postData,
        dataType: "json",
        success: function(re) {
            loadAjax03(re);
        }
    });
}
function loadAjax03(re){
    if (re.Status == 200) {
        requestAjax01();
        $('#modal-overlay').addClass('hidden');
    }else{
        myAlert(re.Message);
    }
}

(function addPicSubmit(){   //替换picModal中的addPicSubmit
    $("#addPicBtn").unbind("click").bind("click",function(){
        var imgs = $(".u_checked>img");
        if(imgs.length>0){
            for(var i=0,html='';i<imgs.length;i++){
                if(_this[0].tagName==='LI'){
                    html = '<img src="'+imgs[0].src+'" alt="">';
                    _this.html(html);
                    _this.parent().prev().val(imgs[0].src.split(PicAddress)[1]);
                }
            }
            $('#picModal').addClass('hidden');
        }
    });
})();


//产品类别排序

function _gridInit(){   //MDM000308
    var _gridData = Object.create(gridData);
    _gridData.url = mdmPath + '/MDM0003/MDM000308';
    _gridData.rowNum = 100;
    _gridData.colModel = [
        //{label:'序号', name:'OrderID'},
        {label:'代码', name:'Code'},
        {label:'名称', name:'Name'}
    ];
    _gridData.sortname = 'OrderID';
    _gridData.beforeRequest = function(){
        _gridData.grid.jqGrid("setGridParam", {
            postData : jg_postData,
        });
    };
    _gridData.loadComplete = function(xhr){ 
        xhr.Status == '-999' && alert_situ($('.u_pane_2').find('.u_table_container'),xhr.Message);
        _gridData.grid.jqGrid('sortableRows',{
            update:function(ev,ui){
                var item = ui.item[0],
                ri = item.rowIndex,
                itemId = item.id;
            }
        });
        var gridData= _grid.jqGrid("getRowData");
        if(!gridData.length){
            console.log('没有子级');
            $('.jg_tip').removeClass('hidden');
        }else{
            $('.jg_tip').addClass('hidden');
        };
    }
    
    gridInit(_gridData);
}

function requestAjax04(){   //MDM000309
    var gridData= _grid.jqGrid("getRowData");
    var st_postData = {
        Method: 'U',
        Content: gridData
    };
    for(i in postData){
        st_postData[i] = postData[i];
    }
    console.log(st_postData)
    $.ajax({
        type: 'post',
        url: mdmPath + '/MDM0003/MDM000309',
        data: st_postData,
        dataType: 'json',
        success: function(re){
            if (re.Status == 200) {
                myAlert('保存成功');
                requestAjax01();
            } else {
                myAlert(re.Message);
            }
        }
    })
}